package com.speechb.config;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.ld.lucenex.analyzer.IKAnalyzer4Lucene7;
import com.ld.lucenex.base.BaseConfig;
import com.ld.lucenex.config.LuceneXConfig;
import com.ld.lucenex.core.LuceneX;
import com.ld.lucenex.service.ServiceFactory;
import com.ld.lucenex.service.ServiceImpl;
import com.speechb.entity.Blog;
import com.speechb.service.IBlogService;
import org.apache.commons.lang3.StringUtils;
import org.apache.lucene.analysis.miscellaneous.PerFieldAnalyzerWrapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.core.Ordered;
import org.springframework.stereotype.Component;

import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.Properties;

/**
 * @author : llj
 * @version :2.1.0
 * @date : 2020/4/8 13:05
 */
@Component
public class MyApplicationRunner implements ApplicationRunner, Ordered {
    private static final Logger LOGGER = LoggerFactory.getLogger(MyApplicationRunner.class);
    private String luceneDataPath;
    @Autowired
    IBlogService blogService;
    /**
     * 通过设置这里数字来知道指定初始化顺序
     * @return
     */
    @Override
    public int getOrder() {
        return 1;
    }

    @Override
    public void run(ApplicationArguments args) throws Exception {
         initLuceneX();
         initLuceneData();
    }

    /**
     * 初始化lucenex
     */
    private void initLuceneX() {
        new LuceneX(new LuceneXConfig() {
            @Override
            public void configLuceneX(BaseConfig me) {
                //获得系统属性集
                Properties props = System.getProperties();
                //操作系统名称
                String osName = props.getProperty("os.name");
                if (osName.contains("Windows") || osName.contains("windows")) {
                    me.add("d:/lucene/data/","mblog", new PerFieldAnalyzerWrapper(new IKAnalyzer4Lucene7()), Blog.class);
                    luceneDataPath = "d:/lucene/data/mblog";
                } else {
                    me.add("/opt/lucene/data/","mblog", new PerFieldAnalyzerWrapper(new IKAnalyzer4Lucene7()), Blog.class);
                    luceneDataPath = "/opt/lucene/data/mblog";
                }
            }
        });
    }

    /**
     * 初始化lucene数据
     * 如果路径没有文件自动初始化数据
     */
    private void initLuceneData() {
        if (StringUtils.isEmpty(luceneDataPath)) {
           LOGGER.error("[initLuceneData]Wrong format of Lucene data path");
        }
        File file = new File(luceneDataPath);
        if (!file.exists()) {
            boolean mkStatus = file.mkdirs();
            if (!mkStatus) {
                LOGGER.error("[initLuceneData]Lucene data folder creation failed");
            }
        }
        if (!file.isDirectory()) {
            LOGGER.error("[initLuceneData]Lucene path is not a folder");
            return;
        }
        String[] list = file.list();
        if (list!=null && list.length>0) {
            LOGGER.error("[initLuceneData]Lucene data has been initialized");
            return;
        }
        try {
            startInitLuceneData();
        } catch (IOException e) {
            LOGGER.error("[initLuceneData]Lucene failed to add data", e);
        }
    }

    private void startInitLuceneData() throws IOException {
        int pageNum = 1;
        int pageSize = 500;
        Page page = PageHelper.startPage(pageNum, pageSize, true);
        List<Blog> speechCraftList = blogService.findLuceneData();
        ServiceImpl<Blog> basisService = ServiceFactory.getService(ServiceImpl.class);
        basisService.addObjects(speechCraftList);
        LOGGER.warn("第一条数据：{}",speechCraftList.get(0));
        for (int i = pageNum; i * pageSize < page.getTotal(); i++) {
            page = PageHelper.startPage(i, pageSize, true);
            speechCraftList = blogService.findLuceneData();
            basisService.addObjects(speechCraftList);

        }
    }
}
